package com.as.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.as.base.BaseController;
import com.as.entity.Rank;
import com.as.entity.User;

@Controller
@RequestMapping("/rank")
public class RankController extends BaseController{
	
	@ResponseBody
	@RequestMapping("/get")
	public Map<String, Object> getRank(HttpSession httpSession){
		Map<String, Object> map = new HashMap<String, Object>();
		User user = (User)httpSession.getAttribute("user");
		Rank rank = rankManager.getRankByUserid(user.getUserid());
		if(rank == null){
			map.put("rank", "0");
			return map;
		}
		int ranks = rankManager.getOneRank(rank.getRighttimes());
		map.put("rank", ranks);
		return map;
	}
	
	@ResponseBody
	@RequestMapping("/add/{rightTimes}")
	public Map<String, Object> addRank(@PathVariable int rightTimes,
			HttpSession httpSession){
		User user = (User)httpSession.getAttribute("user");
		Map<String, Object> map = new HashMap<String, Object>();
		Rank rankAlready = rankManager.getRankByUserid(user.getUserid());
		if(rankAlready == null){
			Rank rankNew = rankManager.createRank(user.getUserid(), rightTimes);
		    if(rankManager.addRank(rankNew)){
		    	int ranks = rankManager.getOneRank(rightTimes);
				map.put("rank", ranks);
		    	map.put("state", "OK");
		    }else{
		    	map.put("rank", "0");
		    	map.put("state", "ERROR");
		    }
		}else{
			rankAlready.setRighttimes(rightTimes);
			if(rankManager.updateRank(rankAlready)){
				int ranks = rankManager.getOneRank(rightTimes);
				map.put("rank", ranks);
		    	map.put("state", "OK");
		    }else{
		    	map.put("rank", "0");
		    	map.put("state", "ERROR");
		    }
		}
		return map;
	}
	
	@ResponseBody
	@RequestMapping("/getTopThree")
	public Map<String, Object> updateRank(){
		Map<String, Object> map = new HashMap<String, Object>();
		List<Object> topList = rankManager.getTopThree();
		map.put("topList", topList);
		return map;
	}

}
